<template>
    <n-space v-if="tags.length" :vertical="props.vertical">
        <template v-for="item in tags" :key="item.id">
            <n-tag :color="map.get(item)" v-bind="attrs">{{ item }}</n-tag>
        </template>
    </n-space>
</template>

<script setup>
import { computed, useAttrs, watchEffect } from 'vue'

const attrs = useAttrs()
const props = 
    defineProps({
        vertical: {
            type: Boolean,
            default: false
        },
        tags: {
            type: [String, Array],
            default: () => []
        },
        splitChar: {
            type: String,
            default: ','
        }
    })

const tags = computed(() =>
    props.tags instanceof Array
        ? props.tags
        : props.tags
        ? props.tags.split(props.splitChar)
        : []
)

const fixedColors = [
    { color: '#bae7ff', textColor: '#096dd9', borderColor: '#69c0ff' },
    { color: '#ffe7ba', textColor: '#d46b08', borderColor: '#ffc069' },
    { color: '#fff1b8', textColor: '#d48806', borderColor: '#ffd666' },
    { color: '#d9f7be', textColor: '#389e0d', borderColor: '#95de64' },
    { color: '#b5f5ec', textColor: '#08979c', borderColor: '#5cdbd3' },
    { color: '#d6e4ff', textColor: '#1d39c4', borderColor: '#85a5ff' },
    { color: '#efdbff', textColor: '#531dab', borderColor: '#b37feb' },
    { color: '#ffebee', textColor: '#ef9a9a', borderColor: '#ffcdd2' },
    { color: '#efebe9', textColor: '#795548', borderColor: '#bcaaa4' },
    { color: '#fbe9e7', textColor: '#ff5722', borderColor: '#ffab91' },
    { color: '#fff3e0', textColor: '#ff9800', borderColor: '#ffcc80' },
    { color: '#ffd6e7', textColor: '#c41d7f', borderColor: '#ff85c0' },
    { color: '#fff8e1', textColor: '#ffc107', borderColor: '#ffe082' },
    { color: '#ffccc7', textColor: '#cf1322', borderColor: '#ff9c6e' },
    { color: '#ffd8bf', textColor: '#d4380d', borderColor: '#ff9c6e' },
    { color: '#fffde7', textColor: '#ffeb3b', borderColor: '#fff59d' },
    { color: '#82b1ff', textColor: '#204bc3', borderColor: '#448aff' },
    { color: '#f1f8e9', textColor: '#8bc34a', borderColor: '#c5e1a5' },
    { color: '#e8f5e9', textColor: '#4caf50', borderColor: '#a5d6a7' },
    { color: '#e8eaf6', textColor: '#3f51b5', borderColor: '#9fa8da' }
]

function hashFn(str, size) {
    let hash = 0
    for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i)
        hash &= hash // 将 hash 转为 32 位整数
    }
    return Math.abs(hash) % size
}

let map = new Map()
watchEffect(() => {
    tags.value.forEach((item) => {
        let index = hashFn(item, fixedColors.length)
        map.set(item, fixedColors[index])
    })
})
</script>

<style scoped></style>
